import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Redirect, Switch } from "react-router-dom";
import { Layout, Menu, Select, Dropdown, Icon, Button, Tabs, Modal, Alert, Form, Input, Tooltip, message, Upload, Table, Popconfirm, Divider, Row, Col, Tag, Checkbox } from 'antd'
import { iconFontUrl, inspectitemUploadTemplateUrl, memberUploadTemplateUrl } from "../js/config.js";
import icon from "../img/icon.png";
import { addMenuApi, allSchoolApi, listMenuApi, deleteMenuApi, updateMenuApi, allDepartmentApi, listPermissionByDepartment, listDefaultPermissionByIdentityApi, updatePermissionsApi, addInspectItemBySchoolIdApi, SchoolAllApi, importPublicMemberListApi } from "../js/api.js"

const { Content, Sider, Header } = Layout;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});

class Permission extends Component {
    constructor(props) {
        super(props);
        let url = document.location.href;
        let page = url.split("/")[5];
        let defaultSelectedKeys;
        switch (page) {
        case "permissionitem":
            defaultSelectedKeys = "permissionitem"; break;
        case "permissionset":
            defaultSelectedKeys = "permissionset"; break;
        case "inspectitemdeploy":
            defaultSelectedKeys = "inspectitemdeploy"; break;
        case "publiclistdeploy":
            defaultSelectedKeys = "publiclistdeploy"; break;
        case "publiczhizhouitemdeploy":
            defaultSelectedKeys = "publiczhizhouitemdeploy"; break;
        default: defaultSelectedKeys = "permissionitem";
        }
        this.state = {
            defaultSelectedKeys: [defaultSelectedKeys],
            collapsed: false,
        };
    }

    onCollapse = (collapsed) => {
        //console.log(collapsed);
        if (collapsed) {
            document.getElementById("logoName").style.display = "none";
        } else {
            document.getElementById("logoName").style.display = "inline";
        }
        this.setState({ collapsed });
    }

    logOff() {
        sessionStorage.setItem("username", null);
        sessionStorage.setItem("identityId", null);
        sessionStorage.setItem("departmentId", null);
        this.props.history.push("/");
    }

    render() {
        return (
            <Router basename="/system/permission">
                <Layout>
                    <Sider
                        collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.onCollapse}
                        width={256}
                        style={{
                            overflow: "auto",
                            height: "100vh",
                            left: 0
                        }}>
                        <div className="logo" >
                            {/* <IconFont type="icon-anfang" className='icon' style={{ verticalAlign: "middle", }} /> */}
                            <img src={icon} className='icon' style={{
                                verticalAlign: 'middle',
                                width: '30px',
                                height: '30px',
                                marginRight: '5px'
                            }} />
                            <div
                                id='logoName'
                                style={{ verticalAlign: 'middle', display: 'inline-block', paddingLeft: "5px" }}>
                                梯度智慧安监
                            </div>
                        </div>
                        <Menu theme="dark" mode="inline" defaultSelectedKeys={this.state.defaultSelectedKeys}>
                            <Menu.Item key="permissionitem">
                                <Link to="/permissionitem">
                                    <IconFont type="icon-daohanglan" className='icon' />
                                    <span className="nav-text">菜单管理</span>
                                </Link>
                            </Menu.Item>
                            <Menu.Item key="permissionset">
                                <Link to="/permissionset">
                                    <IconFont type="icon-nav-_yonghuquanxianpeizhi" className='icon' />
                                    <span className="nav-text">权限配置</span>
                                </Link>
                            </Menu.Item>
                            <Menu.Item key="inspectitemdeploy">
                                <Link to="/inspectitemdeploy">
                                    <IconFont type="icon-42jitixiangmuliebiao" className='icon' />
                                    <span className="nav-text">巡检项配置</span>
                                </Link>
                            </Menu.Item>
                            <Menu.Item key="publiclistdeploy">
                                <Link to="/publiclistdeploy">
                                    <IconFont type="icon-mingdan" className='icon' />
                                    <span className="nav-text">公共名单导入</span>
                                </Link>
                            </Menu.Item>
                            <Menu.Item key="publiczhizhouitemdeploy">
                                <Link to="/publiczhizhouitemdeploy">
                                    <IconFont type="icon-mingdan" className='icon' />
                                    <span className="nav-text">值周项导入</span>
                                </Link>
                            </Menu.Item>
                        </Menu>
                    </Sider>
                    <Layout style={{ height: "100vh" }}>
                        <Header style={{
                            background: '#fcfcfc',
                            padding: 0,
                            fontFamily: 'Microsoft Yahei, sans-serif',
                            fontSize: 15,
                            position: 'relative',
                            height: '64px',
                            lineHeight: '64px',
                        }}>
                            <div style={{ position: "absolute", top: 0, bottom: 0, left: 24, }}>
                                欢迎您！您的身份为<span style={{ color: '#1890ff' }}>权限管理员</span>
                            </div>
                            <div style={{ position: "absolute", top: 0, bottom: 0, right: 24, }}>
                                <Dropdown overlay={
                                    <Menu>
                                        <Menu.Item>
                                            <a
                                                class='logOff'
                                                style={{ color: '#333333', padding: '5px 15px' }}
                                                onClick={() => this.logOff()}>
                                                <IconFont
                                                    type="icon-zhuxiaologout11" className='icon'
                                                    style={{ fontSize: '14px', verticalAlign: 'middle' }} />
                                                <span style={{ verticalAlign: 'middle', marginLeft: '2px' }}>退出登录</span>
                                            </a>
                                        </Menu.Item>
                                    </Menu>
                                }>
                                    <div
                                        className='dropdown'
                                        style={{
                                            padding: '0px 5px'
                                        }}>
                                        <IconFont
                                            style={{ fontSize: '28px', verticalAlign: 'middle' }}
                                            type="icon-touxiang-shi" className='icon' />
                                        <span style={{ marginLeft: '2px' }}>{sessionStorage.getItem("username")}</span>
                                    </div>
                                </Dropdown>
                            </div>
                        </Header>
                        <Content style={{ margin: "24px", overflow: "initial" }}>
                            <div
                                id="right"
                                style={{
                                    padding: 24,
                                    background: "#fff",
                                    height: "auto",
                                    marginBottom: 24
                                }}
                            >
                                <Switch>
                                    <Route path="/permissionitem" component={PermissionItem} />
                                    <Route path="/permissionset" component={PermissionSet} />
                                    <Route path="/inspectitemdeploy" component={Inspectitemdeploy} />
                                    <Route path="/publiclistdeploy" component={Publiclistdeploy} />
                                    {/* <Route path="/publiczhizhouitemdeploy" component={Publiczhizhouitemdeploy} /> */}
                                    <Redirect path="/" to={{ pathname: '/permissionitem' }} />
                                </Switch>
                            </div>
                        </Content>
                        {/* <Footer style={{ textAlign: "center", background: '#fcfcfc', }}>绍兴市教育局</Footer> */}
                    </Layout>
                </Layout>
            </Router>
        );
    }
}

const TabPane = Tabs.TabPane;
class PermissionItem extends Component {
    render() {
        return (
            <div>
                <Tabs
                    tabBarStyle={{
                        width: '180px'
                    }}
                    defaultActiveKey="1"
                    tabPosition="left">
                    <TabPane tab="教育局管理员" key="1">
                        <AddMenu identityId={1} />
                    </TabPane>
                    <TabPane tab="教育局安监处" key="2">
                        <AddMenu identityId={2} />
                    </TabPane>
                    <TabPane tab="安监主任" key="3">
                        <AddMenu identityId={4} />
                    </TabPane>
                    <TabPane tab="学校管理员" key="4">
                        <AddMenu identityId={3} />
                    </TabPane>
                    <TabPane tab="学校教师" key="5">
                        <AddMenu identityId={8} />
                    </TabPane>
                </Tabs>
            </div>
        );
    }
}

class AddMenu extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addMenu: false,
            confirmLoading: false,
            alertVisible: false,
            msg: '',
            tableLoading: false,
            tableData: [],
            addMenuType: 'addMenu',
            parent: 0,
            updateMenu: false,
            updateInitValue: {}
        };
    }

    componentDidMount() {
        this.refreshData(this.props.identityId);
    }

    refreshData(identityId) {
        this.setState({
            tableLoading: true
        });
        listMenuApi(identityId)
            .then(res => {
                this.setState({
                    tableData: res.data,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    // target = addSubMenu时第二个参数为parent
    // target = updateMenu时第二个参数为updateInitValue
    showModal = (target, param) => {
        if (target == "addMenu") {
            this.setState({
                addMenu: true,
                addMenuType: "addMenu",
                parent: 0
            });
        }
        if (target == "addSubMenu") {
            this.setState({
                addMenu: true,
                addMenuType: "addSubMenu",
                parent: param
            });
        }
        if (target == "updateMenu") {
            this.setState({
                updateMenu: true,
                updateInitValue: param
            });
        }
    }

    // 关闭模态框
    handleCancel = (target) => {
        this.setState({
            alertVisible: false
        });
        if (target == "addMenu") {
            let val = this.refs.addMenuFormValue;
            val.resetFields();
            this.setState({
                addMenu: false
            });
        }
        if (target == "updateMenu") {
            let val = this.refs.updateMenuFormValue;
            val.resetFields();
            this.setState({
                updateMenu: false
            });
        }
    }

    // 关闭模态框错误提示
    handleClose = () => {
        this.setState({ alertVisible: false });
    }

    addMenuSubmit = (type) => {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addMenuFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                let parent = 0;
                let order = 0;
                if (type == "addMenu") {
                    parent = 0;
                    if (this.state.tableData.length > 0) {
                        order = this.state.tableData[this.state.tableData.length - 1].order + 1;
                    } else {
                        order = 1;
                    }
                } else if (type == "addSubMenu") {
                    parent = this.state.parent;
                    let parentIndex = 0;
                    for (let i = 0; i < this.state.tableData.length; i++) {
                        if (this.state.tableData[i].id == parent) {
                            parentIndex = i;
                            break;
                        }
                    }
                    console.log(parentIndex)
                    order = this.state.tableData[parentIndex].subMenu.length === 0 ?
                        1 : this.state.tableData[parentIndex].subMenu[this.state.tableData[parentIndex].subMenu.length - 1].order + 1;
                }
                console.log(order);
                addMenuApi(values, parent, this.props.identityId, order)
                    .then(res => {
                        if (res.data == "success") {
                            message.success("新增菜单成功！");
                            this.refreshData(this.props.identityId);
                            this.handleCancel("addMenu"); //关闭模态框
                        } else if (res.data == "contained") {
                            this.setState({
                                alertVisible: true,
                                msg: "路由地址已存在，请修改路由地址！"
                            });
                        } else {
                            this.setState({
                                alertVisible: true,
                                msg: "新增菜单失败，请检查表单内容！"
                            });
                        }
                        this.setState({
                            confirmLoading: false
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        })
    }

    handleDeleteMenu = (menuId) => {
        deleteMenuApi(menuId)
            .then(res => {
                if (res.data == "success") {
                    message.success("删除成功！");
                    this.refreshData(this.props.identityId);
                } else {
                    message.success("删除失败！");
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    updateMenuSubmit = (id) => {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.updateMenuFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                updateMenuApi(values, id)
                    .then(res => {
                        if (res.data == "success") {
                            message.success("修改菜单成功！");
                            this.refreshData(this.props.identityId);
                            this.handleCancel("updateMenu"); //关闭模态框
                        } else if (res.data == "contained") {
                            this.setState({
                                alertVisible: true,
                                msg: "路由地址已存在，请修改路由地址！"
                            });
                        } else {
                            this.setState({
                                alertVisible: true,
                                msg: "修改菜单失败，请检查表单内容！"
                            });
                        }
                        this.setState({
                            confirmLoading: false
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        })
    }

    render() {
        let columns = [{
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (text, record, index) => `${index + 1}`,
        }, {
            title: '菜单名称',
            dataIndex: 'name',
            key: 'name'
        }, {
            title: '路由地址',
            dataIndex: 'route',
            key: 'route'
        }, {
            title: 'key',
            dataIndex: 'key',
            key: 'key'
        }, {
            title: 'icon',
            dataIndex: 'icon',
            key: 'icon',
            render: (text, record) => {
                return (
                    <IconFont
                        type={text}
                        className='icon' />
                );
            }
        }, {
            title: '操作详情',
            key: 'action',
            render: (text, record) => (
                <span>
                    <a
                        href="#"
                        onClick={() => {
                            this.showModal("updateMenu", {
                                id: record.id,
                                name: record.name,
                                route: record.route,
                                key: record.key,
                                icon: record.icon
                            })
                        }}>
                        修改
                    </a>
                    {
                        record.parent == 0 ?
                            (
                                <span>
                                    <Divider type="vertical" />
                                    <a href="#" onClick={() => { this.showModal("addSubMenu", record.id) }}>新增二级菜单</a>
                                </span>
                            ) :
                            null
                    }
                    <Divider type="vertical" />
                    <Popconfirm
                        title={
                            record.subMenu != null ?
                                (record.subMenu.length == 0 ? "确定删除？" : "确定同时删除二级菜单？") :
                                "确定删除？"
                        } okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDeleteMenu(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
        let columns2 = [{
            title: '菜单名称',
            dataIndex: 'name',
            key: 'name',
            width: '20%',
        }, {
            title: '路由地址',
            dataIndex: 'route',
            key: 'route',
            width: '25%',
        }, {
            title: 'key',
            dataIndex: 'key',
            key: 'key',
            width: '25%',
        }, {
            title: 'icon',
            dataIndex: 'icon',
            key: 'icon',
            width: '10%',
            render: (text, record) => {
                return (
                    <IconFont
                        type={text}
                        className='icon' />
                );
            }
        }, {
            title: '操作详情',
            key: 'action',
            width: '20%',
            render: (text, record) => (
                <span>
                    <a
                        href="#"
                        onClick={() => {
                            this.showModal("updateMenu", {
                                id: record.id,
                                name: record.name,
                                route: record.route,
                                key: record.key,
                                icon: record.icon
                            })
                        }}>
                        修改
                    </a>
                    {
                        record.parent == 0 ?
                            (
                                <span>
                                    <Divider type="vertical" />
                                    <a href="#" onClick={() => { this.showModal("addSubMenu", record.id) }}>新增二级菜单</a>
                                </span>
                            ) :
                            null
                    }
                    <Divider type="vertical" />
                    <Popconfirm
                        title={
                            record.subMenu != null ?
                                (record.subMenu.length == 0 ? "确定删除？" : "确定同时删除二级菜单？") :
                                "确定删除？"
                        } okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDeleteMenu(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={() => { this.showModal("addMenu") }} size="large">
                        <Icon type="plus" />新增
                    </Button>
                    <Modal
                        title={this.state.addMenuType == "addMenu" ? "新增菜单" : "新增二级菜单"}
                        width={1000}
                        visible={this.state.addMenu}
                        onCancel={() => { this.handleCancel("addMenu") }}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={() => { this.addMenuSubmit(this.state.addMenuType) }}>提交</Button>
                        ]}
                    >
                        <AddMenuForm ref="addMenuFormValue" identityId={this.props.identityId} />
                        {
                            this.state.alertVisible ?
                                (
                                    <Row>
                                        <Col offset={5} span={14}>
                                            <Alert message={this.state.msg} type="error" closable afterClose={() => { this.handleClose() }} />
                                        </Col>
                                    </Row>
                                ) : null
                        }
                    </Modal>
                    <Modal
                        title="修改菜单"
                        width={1000}
                        visible={this.state.updateMenu}
                        onCancel={() => { this.handleCancel("updateMenu") }}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={() => { this.updateMenuSubmit(this.state.updateInitValue.id) }}>保存</Button>
                        ]}
                    >
                        {/* 复用addmenu表单 */}
                        <AddMenuForm ref="updateMenuFormValue"
                            identityId={this.props.identityId}
                            updateInitValue={this.state.updateInitValue} />
                        {
                            this.state.alertVisible ?
                                (
                                    <Row>
                                        <Col offset={5} span={14}>
                                            <Alert message={this.state.msg} type="error" closable afterClose={() => { this.handleClose() }} />
                                        </Col>
                                    </Row>
                                ) : null
                        }
                    </Modal>
                </div>
                <Table
                    dataSource={this.state.tableData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.tableData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                    expandedRowRender={record => {
                        return (
                            <Table
                                dataSource={record.subMenu}
                                columns={columns2}
                                size='small'
                                locale={{ emptyText: '该一级菜单无下属二级菜单' }}
                                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                                showHeader={record.subMenu.length == 0 ? false : true}
                                pagination={false}
                                bordered={true}
                            />
                        )
                    }} />
            </div>
        )
    }
}

const FormItem = Form.Item;
class addMenuForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            preRoute: '',
            name: props.updateInitValue == undefined ? "" : props.updateInitValue.name,
            route: props.updateInitValue == undefined ? "" : props.updateInitValue.route,
            key: props.updateInitValue == undefined ? "" : props.updateInitValue.key,
            icon: props.updateInitValue == undefined ? "" : props.updateInitValue.icon
        }
    }

    componentWillReceiveProps(props) {
        this.setState({
            name: props.updateInitValue == undefined ? "" : props.updateInitValue.name,
            route: props.updateInitValue == undefined ? "" : props.updateInitValue.route,
            key: props.updateInitValue == undefined ? "" : props.updateInitValue.key,
            icon: props.updateInitValue == undefined ? "" : props.updateInitValue.icon
        });
    }

    componentDidMount() {
        switch (this.props.identityId) {
        case 1:
            this.setState({
                preRoute: 'http://tidukeji.cn/edudepartment/admin'
            });
            break; //教育局管理员
        case 2:
            this.setState({
                preRoute: 'http://tidukeji.cn/edudepartment/safetysupervisor'
            });
            break; //教育局安监处
        case 3:
            this.setState({
                preRoute: 'http://tidukeji.cn/school/admin'
            });
            break; //学校管理员
        case 4:
            this.setState({
                preRoute: 'http://tidukeji.cn/school/safetysupervisor'
            });
            break; //学校安监主任
        case 5:
            break; //学校分管副校长
        case 8:
            this.setState({
                preRoute: 'http://tidukeji.cn/school/teacher'
            });
            break; //学校教师
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };
        return (
            <Form>
                <FormItem
                    label='名称'
                    {...formItemLayout}>
                    {getFieldDecorator("name", {
                        initialValue: this.state.name,
                        rules: [{
                            required: true,
                            message: "请输入菜单名称!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <IconFont type="icon-mingcheng" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="菜单名称"
                        />
                    )}
                </FormItem>
                <FormItem
                    label={(
                        <span>
                            路由地址&nbsp;
                            <Tooltip title="相对地址">
                                <Icon type="question-circle-o" />
                            </Tooltip>
                        </span>
                    )}
                    {...formItemLayout}>
                    {getFieldDecorator("route", {
                        initialValue: this.state.route,
                        rules: [{
                            required: true,
                            message: "请输入路由地址!"
                        }, {
                            required: false,
                            pattern: new RegExp(/^\/.+$/, "g"),
                            message: '请以“/”开头填写路由地址'
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <IconFont type="icon-luyou" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            addonBefore={this.state.preRoute}
                            placeholder="路由地址"
                        />
                    )}
                </FormItem>
                <FormItem
                    label={(
                        <span>
                            key&nbsp;
                            <Tooltip title="key值用于改变导航栏菜单高亮和展开">
                                <Icon type="question-circle-o" />
                            </Tooltip>
                        </span>
                    )}
                    {...formItemLayout}>
                    {getFieldDecorator("key", {
                        initialValue: this.state.key,
                        rules: [{
                            required: true,
                            message: "请输入key值!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <IconFont type="icon-key" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="key"
                        />
                    )}
                </FormItem>
                <FormItem
                    label={(
                        <span>
                            icon&nbsp;
                            <Tooltip title="icon值为项目矢量图库图标代码">
                                <Icon type="question-circle-o" />
                            </Tooltip>
                        </span>
                    )}
                    {...formItemLayout}>
                    {getFieldDecorator("icon", {
                        initialValue: this.state.icon,
                        rules: [{
                            required: true,
                            message: "请输入icon值!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <IconFont type="icon-tubiao" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="icon"
                        />
                    )}
                </FormItem>
            </Form>
        );
    }
}
const AddMenuForm = Form.create()(addMenuForm);

class PermissionSet extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tableData: [],
            tableLoading: false
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        allDepartmentApi()
            .then(res => {
                this.setState({
                    tableData: res.data,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        // 外部表格表头
        const departmentColumns = [{
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (text, record, index) => `${index + 1}`
        }, {
            title: '类型',
            dataIndex: 'type',
            key: 'type'
        }, {
            title: '单位名称',
            dataIndex: 'name',
            key: 'name'
        }, {
            title: '地址',
            dataIndex: 'address',
            key: 'address'
        }];
        return (
            <div>
                <Table
                    dataSource={this.state.tableData}
                    columns={departmentColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    expandedRowRender={record => {
                        return (
                            <PermissionInnerTable
                                departmentId={record.id}
                                departmentName={record.name}
                            />
                        )
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.tableData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        );
    }
}

class PermissionInnerTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tableLoading: true,
            tableData: [],
            departmentId: props.departmentId,
            departmentName: props.departmentName,
            mouseEnterRow: '',
            modal: false,
            alertVisible: false,
            msg: '',
            identity: '',
            identityId: 0,
            permissions: [],
            confirmLoading: false
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        listPermissionByDepartment(this.state.departmentId)
            .then(res => {
                this.setState({
                    tableLoading: false,
                    tableData: res.data
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    showModal = (record) => {
        this.setState({
            modal: true,
            identity: record.identity,
            identityId: record.identityId,
            permissions: record.permissions
        });
    }

    // 关闭模态框
    handleCancel = () => {
        let val = this.refs.permissionSetFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            msg: '',
            modal: false,
            identity: '',
            identityId: 0
        });
    }

    // 关闭模态框错误提示
    handleClose = () => {
        this.setState({ alertVisible: false });
    }

    permissionSet = () => {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.permissionSetFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                updatePermissionsApi(this.state.departmentId, this.state.identityId, values.permissions)
                    .then(res => {
                        if (res.data == "success") {
                            message.success("权限配置成功！");
                            this.handleCancel(); //关闭模态框
                            this.refreshData();
                        } else {
                            this.setState({
                                alertVisible: true,
                                msg: "权限配置失败，请检查表单信息！"
                            });
                        }
                        this.setState({
                            confirmLoading: false
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        })
    }

    render() {
        // 内部表格表头
        const identityColumns = [{
            title: '用户角色',
            dataIndex: 'identity',
            key: 'identity',
            width: '15%',
        }, {
            title: '权限',
            dataIndex: 'permissions',
            key: 'permissions',
            width: '70%',
            render: (text, record, index) => {
                const tags = record.permissions.map(row => <Tag color='blue'>{row.name}</Tag>)
                return (
                    <div>
                        {tags}
                    </div>
                );
            }
        }, {
            title: "操作详情",
            key: "action",
            width: '15%',
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={() => this.showModal(record)}>权限配置</a>
                </span>
            )
        }];
        return (
            <div>
                <Table
                    columns={identityColumns}
                    dataSource={this.state.tableData}
                    pagination={false}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    bordered={true}
                    rowClassName={(record, index) => {
                        let className = ''
                        index % 2 === 0 ? className = "mytr rowOne" : className = "mytr rowTwo";
                        record.identity === this.state.mouseEnterRow ? className += " mouseEnterRow" : className += "";
                        return className;
                    }}
                    onRow={(record) => {
                        return {
                            onMouseEnter: (event) => {
                                this.setState({
                                    mouseEnterRow: record.identity
                                });
                            },  // 鼠标移入行
                            onMouseLeave: (event) => {
                                this.setState({
                                    mouseEnterRow: ''
                                });
                            }
                        };
                    }}
                />
                <Modal
                    title="权限配置"
                    width={1000}
                    visible={this.state.modal}
                    onCancel={() => { this.handleCancel() }}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                            loading={this.state.confirmLoading}
                            onClick={() => { this.permissionSet() }}>保存</Button>
                    ]}
                >
                    <PermissionSetForm
                        ref="permissionSetFormValue"
                        identity={this.state.identity}
                        identityId={this.state.identityId}
                        departmentName={this.state.departmentName}
                        permissions={this.state.permissions}
                    />
                    {
                        this.state.alertVisible ?
                            (
                                <Row>
                                    <Col offset={5} span={14}>
                                        <Alert message={this.state.msg} type="error" closable afterClose={() => { this.handleClose() }} />
                                    </Col>
                                </Row>
                            ) : null
                    }
                </Modal>
            </div>
        );
    }
}

class permissionSetForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            identity: props.identity,
            identityId: props.identityId,
            departmentName: props.departmentName,
            permissions: props.permissions,
            initPermissions: [],
            allPermissions: []
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    componentWillReceiveProps(props) {
        this.setState({
            identity: props.identity,
            identityId: props.identityId,
            departmentName: props.departmentName,
            permissions: props.permissions
        });
        this.refreshData();
        console.log("---------------props.permissions:"+props.permissions)
    }

    refreshData() {
        let initPermissions = [];
        this.state.permissions.forEach(val => {
            initPermissions.push(val.id);
        });
        this.setState({
            initPermissions: initPermissions
        });
        listDefaultPermissionByIdentityApi(this.state.identityId)
            .then(res => {
                this.setState({
                    allPermissions: res.data
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };

        const checkbox = this.state.allPermissions.map(val => <Col span={6}><Checkbox value={val.id}>{val.name}</Checkbox></Col>);

        return (
            <Form>
                <FormItem
                    label='单位名称'
                    {...formItemLayout}>
                    {getFieldDecorator("department", {
                        initialValue: this.state.departmentName
                    })(
                        <Input
                            size="large"
                            prefix={
                                <IconFont type="icon-jiaoyuju" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="单位名称"
                            disabled={true}
                        />
                    )}
                </FormItem>
                <FormItem
                    label='用户角色'
                    {...formItemLayout}>
                    {getFieldDecorator("identity", {
                        initialValue: this.state.identity
                    })(
                        <Input
                            size="large"
                            prefix={
                                <IconFont type="icon-team" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="用户角色"
                            disabled={true}
                        />
                    )}
                </FormItem>
                <FormItem
                    label='权限'
                    {...formItemLayout}>
                    {getFieldDecorator("permissions", {
                        initialValue: this.state.initPermissions
                    })(
                        <Checkbox.Group style={{
                            width: "100%",
                            lineHeight: 'inherit'
                        }}>
                            <Row>
                                {checkbox}
                            </Row>
                        </Checkbox.Group>
                    )}
                </FormItem>
            </Form>
        );
    }
}

const PermissionSetForm = Form.create()(permissionSetForm);

class inspectitemdeploy extends Component {
    constructor(props) {
        super(props);
        this.state = {
            members: [],
            schoolId: 0,
            fileList: [],
            uploading: false,

        }
    }

    componentDidMount() {
        const avaliablemembers = [];
        SchoolAllApi()
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    avaliablemembers.push({
                        name: item.name,
                        value: item.id,
                        address: item.address
                    });
                });
                this.setState({
                    members: avaliablemembers
                })
            })

    }

    handleSubmit = e => {
        e.preventDefault();
        const { fileList } = this.state;
        // console.log(fileList);
        const formData = new FormData();
        fileList.forEach((file) => {
            formData.append('upfile', file);
        });
        this.setState({
            uploading: true,
        });
        this.props.form.validateFields((err, values) => {
            if (!err) {
                formData.append('schoolId', values.schoolId);
                console.log(formData.get("schoolId"));
                addInspectItemBySchoolIdApi(formData)
                    .then(res => {
                        if (res.data === "success") {
                            message.success("上传成功！");
                            this.props.form.resetFields();
                        } else {
                            message.error(res.data);
                        }
                        this.setState({
                            uploading: false,
                            fileList: [],
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message);
                        }
                        console.info(e.config)
                    });
            }
        });
    };

    render() {
        const { uploading, fileList } = this.state;
        const { getFieldDecorator } = this.props.form;
        const avaliablemembers = this.state.members.map((d, index) =>
            <Option value={d.value} key={index}>
                {d.name}
            </Option>);

        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 8 },
        };

        const tailFormItemLayout = {
            wrapperCol: {
                offset: 8,
                span: 8
            },
        };

        const props = {
            onRemove: (file) => {
                this.setState((state) => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file) => {
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };

        return (
            <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                <Form.Item label="单位">
                    {getFieldDecorator('schoolId', {
                        rules: [
                            {
                                required: true,
                                message: '请选择一个学校',
                            },
                        ],
                    })(<Select
                        style={{
                            width: '100%'
                        }}
                        size="large"
                        placeholder="选择学校">
                        {avaliablemembers}
                    </Select>)}
                </Form.Item>

                <Form.Item label="选择文件">
                    {getFieldDecorator('message', {
                        rules: [
                            {
                                required: true,
                                message: '请上传文件',
                            },
                        ],
                    })(
                        <Upload {...props}>
                            {
                                this.state.fileList.length === 0 ?
                                    (
                                        <Button >
                                            <Icon type="upload" />选择文件
                                        </Button>
                                    ) :
                                    (
                                        null
                                    )
                            }
                        </Upload>
                    )}
                </Form.Item>

                <Form.Item {...tailFormItemLayout}>
                    <Button href={inspectitemUploadTemplateUrl}  ><Icon type="download" />下载模板</Button>
                </Form.Item>

                <Form.Item {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                </Form.Item>
            </Form>

        )
    }
}
const Inspectitemdeploy = Form.create()(inspectitemdeploy);

class publiclistdeploy extends Component {
    constructor(props) {
        super(props);
        this.state = {
            members: [],
            schoolId: 0,
            fileList: [],
            uploading: false,

        }
    }

    componentDidMount() {
        const avaliablemembers = [];
        SchoolAllApi()
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    avaliablemembers.push({
                        name: item.name,
                        value: item.id,
                        address: item.address
                    });
                });
                this.setState({
                    members: avaliablemembers
                })
            })

    }

    handleSubmit = e => {
        e.preventDefault();
        const { fileList } = this.state;
        // console.log(fileList);
        const formData = new FormData();
        fileList.forEach((file) => {
            formData.append('upfile', file);
        });
        this.setState({
            uploading: true,
        });
        this.props.form.validateFields((err, values) => {
            if (!err) {
                formData.append('schoolId', values.schoolId);
                formData.append('name', values.name);
                importPublicMemberListApi(formData)
                    .then(res => {
                        if (res.data === "success") {
                            message.success("上传成功！");
                            this.props.form.resetFields();
                        } else {
                            message.error(res.data);
                        }
                        this.setState({
                            uploading: false,
                            fileList: [],
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message);
                        }
                        console.info(e.config)
                    });
            }
        });
    };

    render() {
        const text = "该功能只添加教师的公共分组"
        const { uploading, fileList } = this.state;
        const { getFieldDecorator } = this.props.form;
        const avaliablemembers = this.state.members.map((d, index) =>
            <Option value={d.value} key={index}>
                {d.name}
            </Option>);

        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 8 },
        };

        const tailFormItemLayout = {
            wrapperCol: {
                offset: 8,
                span: 8
            },
        };

        const props = {
            onRemove: (file) => {
                this.setState((state) => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file) => {
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };

        return (
            <Form {...formItemLayout}>
                <Form.Item label="单位">
                    {getFieldDecorator('schoolId', {
                        rules: [
                            {
                                required: true,
                                message: '请选择一个学校',
                            },
                        ],
                    })(<Select
                        style={{
                            width: '100%'
                        }}
                        size="large"
                        placeholder="选择学校">
                        {avaliablemembers}
                    </Select>)}
                </Form.Item>

                <Form.Item label="分组名称">
                    {getFieldDecorator('name', {
                        rules: [
                            {
                                required: true,
                                message: '请输入分组名称',
                            },
                        ],
                    })(<Input
                        style={{
                            width: '100%'
                        }}
                        size="large"
                        placeholder="输入分组名称">
                    </Input>)}
                </Form.Item>

                <Form.Item label="选择文件">
                    {getFieldDecorator('message', {
                        rules: [
                            {
                                required: true,
                                message: '请上传文件',
                            },
                        ],
                    })(
                        <Upload {...props}>
                            {
                                this.state.fileList.length === 0 ?
                                    (
                                        <Button >
                                            <Icon type="upload" />选择文件
                                        </Button>
                                    ) :
                                    (
                                        null
                                    )
                            }
                        </Upload>
                    )}
                </Form.Item>

                <Form.Item {...tailFormItemLayout}>
                    <Button href={memberUploadTemplateUrl}  ><Icon type="download" />下载模板</Button>
                </Form.Item>

                <Form.Item {...tailFormItemLayout}>
                    <Popconfirm placement="topLeft" title={text} onConfirm={this.handleSubmit} okText="Yes" cancelText="No">
                        <Button type="primary">
                            提交
                        </Button>
                    </Popconfirm>
                </Form.Item>
            </Form>

        )
    }
}
const Publiclistdeploy = Form.create()(publiclistdeploy);



export default Permission;
export { PermissionSet, Inspectitemdeploy, Publiclistdeploy, PermissionItem,  };